<template>
  <div class="flex flex-col h-full">
    <!-- 聊天头部 -->
    <div class="flex items-center justify-between px-4 py-3 border-b border-gray-100">
      <div class="flex items-center justify-center flex-1">
        <el-avatar :size="40" :src="currentSession?.targetAvatar" />
        <div class="ml-3">
          <h3 class="text-base font-medium text-gray-900">{{ currentSession?.targetName }}</h3>
          <p class="text-sm text-gray-500">{{ currentSession?.type === ChatSessionType.PRIVATE ? '私聊' : '群聊' }}</p>
        </div>
      </div>
      <div class="flex items-center space-x-3">
        <button class="text-gray-400 hover:text-gray-600">
          <el-icon :size="20">
            <VideoCamera />
          </el-icon>
        </button>
        <button class="text-gray-400 hover:text-gray-600">
          <el-icon :size="20">
            <Phone />
          </el-icon>
        </button>
        <el-dropdown trigger="click">
          <button class="text-gray-400 hover:text-gray-600">
            <el-icon :size="20">
              <More />
            </el-icon>
          </button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>查看资料</el-dropdown-item>
              <el-dropdown-item>清空聊天记录</el-dropdown-item>
              <el-dropdown-item>举报</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 聊天消息列表 -->
    <div class="flex-1 overflow-y-auto p-4 space-y-4" ref="messageListRef">
      <template v-for="message in messages" :key="message.id">
        <!-- 对方的消息 -->
        <div v-if="message.senderId !== userStore.userInfo?.id" class="flex items-start">
          <el-avatar :size="36" :src="currentSession?.targetAvatar" class="flex-shrink-0" />
          <div class="ml-2 max-w-[70%]">
            <div class="bg-white rounded-lg p-3 shadow-sm">
              <p class="text-gray-900">{{ message.content }}</p>
            </div>
            <span class="text-xs text-gray-400 mt-1 block">{{ formatRelativeTime(message.createdAt) }}</span>
          </div>
        </div>

        <!-- 自己的消息 -->
        <div v-else class="flex items-start justify-end">
          <div class="mr-2 max-w-[70%]">
            <div class="bg-blue-500 rounded-lg p-3 shadow-sm">
              <p class="text-white">{{ message.content }}</p>
            </div>
            <span class="text-xs text-gray-400 mt-1 block text-right">{{ formatRelativeTime(message.createdAt) }}</span>
          </div>
          <el-avatar :size="36" :src="userStore.userInfo?.avatar" class="flex-shrink-0" />
        </div>
      </template>
    </div>

    <!-- 底部工具栏和输入框 -->
    <div class="border-t border-gray-100">
      <!-- 工具栏 -->
      <div class="px-4 py-2 flex items-center space-x-2">
        <button class="text-gray-400 hover:text-gray-600">
          <el-icon :size="20">
            <Picture />
          </el-icon>
        </button>
        <button class="text-gray-400 hover:text-gray-600">
          <el-icon :size="20">
            <Files />
          </el-icon>
        </button>
        <button class="text-gray-400 hover:text-gray-600">
          <el-icon :size="20">
            <Mic />
          </el-icon>
        </button>
        <button class="text-gray-400 hover:text-gray-600">
          <el-icon :size="20">
            <VideoPlay />
          </el-icon>
        </button>
      </div>

      <!-- 输入框区域 -->
      <div class="px-4 py-3">
        <div class="flex items-end">
          <el-input v-model="messageInput" type="textarea" :rows="3" placeholder="输入消息..." resize="none"
            @keydown="handleKeydown" :disabled="isSending" />
          <el-button type="primary" class="ml-3 px-6 h-[82px]" @click="sendMessage" :loading="isSending"
            :disabled="!messageInput.trim()">
            发送
          </el-button>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, onUnmounted, nextTick } from 'vue'
import { storeToRefs } from 'pinia'
import {
  VideoCamera,
  Phone,
  More,
  Picture,
  Files,
  Mic,
  VideoPlay
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/useUserStore'
import { useChatSessionStore } from '@/stores/useChatSessionStore'
import { sendPrivateMessage, getPrivateMessages } from '@/api/message'
import { ChatSessionType, MessageType } from '@/types'
import { formatRelativeTime } from '@/utils/datetime'
import { useChatStore } from '@/stores/useChatStore'
import { ElMessage } from 'element-plus'

// 用户状态管理
const userStore = useUserStore()
// 聊天会话状态管理
const chatSessionStore = useChatSessionStore()
// 聊天状态管理
const chatStore = useChatStore()
// 当前选中的会话
const { currentSession } = storeToRefs(chatSessionStore)
// 当前会话的消息列表
const messages = computed(() => chatStore.currentMessages)

// 消息输入框的值
const messageInput = ref('')
// 发送按钮loading状态
const isSending = ref(false)

// 消息列表DOM引用,用于滚动
const messageListRef = ref<HTMLElement>()

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (messageListRef.value) {
    messageListRef.value.scrollTop = messageListRef.value.scrollHeight
  }
}

// 发送消息
const sendMessage = async () => {
  const content = messageInput.value.trim()
  if (!content || !currentSession.value) {
    return
  }

  isSending.value = true

  try {
    const response = await sendPrivateMessage(
      currentSession.value.targetId,
      content,
      MessageType.TEXT
    )

    if (response.code === 200) {
      // 清空输入框
      messageInput.value = ''
      // 添加到消息列表
      chatStore.addMessage(response.data)
      // 滚动到底部
      scrollToBottom()
    } else {
      ElMessage.error(response.message || '发送失败')
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败，请重试')
  } finally {
    isSending.value = false
  }
}

// 处理回车发送
const handleKeydown = (e: KeyboardEvent) => {
  if (e.key === 'Enter' && !e.shiftKey) {
    e.preventDefault()
    sendMessage()
  }
}

// 加载历史消息
const loadHistoryMessages = async () => {
  if (currentSession.value) {
    try {
      const response = await getPrivateMessages(currentSession.value.targetId)
      if (response.code === 200) {
        // 将消息列表反转为正序（最早的消息在前）
        const sortedMessages = [...response.data.records].reverse()
        chatStore.setMessages(sortedMessages)
        scrollToBottom()
      }
    } catch (error) {
      console.error('加载历史消息失败:', error)
    }
  }
}

// 监听会话变化
watch(() => currentSession.value?.id, (newId) => {
  if (newId) {
    // 设置当前会话ID
    chatStore.setCurrentSessionId(newId)
    // 加载新会话的消息
    loadHistoryMessages()
  } else {
    // 清空消息列表
    chatStore.clearMessages()
  }
}, { immediate: true })

// 组件挂载时
onMounted(() => {
  // 添加消息处理器
  chatStore.initWebSocket()
})

// 组件卸载时
onUnmounted(() => {
  // 移除消息处理器
  chatStore.cleanupWebSocket()
})

</script>

<style scoped>
/* 自定义滚动条样式 */
.overflow-y-auto {
  scrollbar-width: thin;
  scrollbar-color: #E5E7EB transparent;
}

.overflow-y-auto::-webkit-scrollbar {
  width: 6px;
}

.overflow-y-auto::-webkit-scrollbar-track {
  background: transparent;
}

.overflow-y-auto::-webkit-scrollbar-thumb {
  background-color: #E5E7EB;
  border-radius: 3px;
}

.overflow-y-auto::-webkit-scrollbar-thumb:hover {
  background-color: #D1D5DB;
}
</style>